//
//  WmcCloudMineVC.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/30.
//

import UIKit
import YPBedrock

// MARK: - 扩展WmcCloudMineVC + WmcNavigatorProtocol

extension WmcCloudMineVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.cloudAlbumMine]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        var vm = WmcCloudMineVM()
        if let viewModel = parms.context as? WmcCloudMineVM {
            vm = viewModel
        }
        let vc = WmcCloudMineVC(vm)
        return vc
    }
}

// MARK: - 扩展WmcCloudMineVC + WmcVMProtocol

extension WmcCloudMineVC: WmcVMProtocol {
    typealias VMType = WmcCloudMineVM
}

// MARK: - [WmcCloudMineVC]

class WmcCloudMineVC: WmcBaseVC {
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        makeNavView(style: .white, showShadow: false)
        self.addNaviLineView()

        viewModel.loadList()
        updateData()
    }

    // Internal

    lazy var tableView: UITableView = {
        let tableView = UITableView.YP.Create(style: .grouped, delegate: self, dataSource: self, registers: [
            YPRegister(WmcCloudMineCell.self),
        ])
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        return tableView
    }()

    override func makeUI() {
        makeNavView(showShadow: false)
        title = "个人资料"

        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
    }

    /// 选择头像
    func showSheetOfChooseAavatar(showSheet: Bool) {
        if showSheet {
            let sheet = WmcSheetView()
            sheet.title = "上传照片"
            sheet.items = ["拍照", "相册"]
            sheet.show(height: 250)
            sheet.didSelectIndexBlock = { [weak self] index in
                guard let weakSelf = self else { return }
                switch index {
                case 0:
                    let cameraStatus = WmcAuthorizedManager.camera()
                    if cameraStatus.info.isAvailable {
                        weakSelf.takePhoto()
                    } else {
                        WmcAuthorizedManager.showCameraPermissionAlert()
                    }
                case 1:
                    let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
                    if photoAlbumStatus.info.isAvailable {
                        weakSelf.selectPhoto()
                    } else {
                        WmcAuthorizedManager.handleAlbumAuthorizationNotAvailable()
                    }
                default: break
                }
            }
        } else {
            /// 更换头像直接跳转
            let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
            if photoAlbumStatus.info.isAvailable {
                selectPhoto()
            } else {
                WmcAuthorizedManager.handleAlbumAuthorizationNotAvailable()
            }
        }
    }

    // Private

//    override func bindViewModel() {
//        #if DEBUG
//            registerDevTool()
//        #endif
//    }

    private func updateData() {
        viewModel.queryUserInfo { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.tableView.reloadData()
        }
    }

    private func takePhoto() {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .camera
        YPApp.CurrentVC?.present(imagePicker, animated: true, completion: nil)
    }

    private func selectPhoto() {
        WmcPhotoSelectManager.photoSelect(vc: YPApp.CurrentVC, maxCount: 1) { [weak self] imgs in
            guard let img = imgs.yp.object(at: 0), let weakSelf = self else { return }
            /// 选择照片上传头像需要裁剪

//            /// 选择照片上传头像需要裁剪
//            let vm = WmcAvatarCropVM()
//            vm.image = img
//            vm.croppingImageBlock = {[weak self] croppedImg in
//                guard let weakSelf = self else { return }
//                weakSelf.updateAvatar(croppedImg: croppedImg)
//            }
//
//            DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
//                WmcNavigatorManager.push(.avatarCropping, parms: vm)
//            }
//

            let cropper = WmcCropperViewController(originalImage: img)

            cropper.delegate = self
            weakSelf.navigationController?.pushViewController(cropper, animated: true)

//            let vm = WmcImageTailorVM()
//            vm.image = WmcImage.init(uiImage: img)
//            WmcNavigatorManager.push(.imageTailor, parms: vm)
//            vm.croppingImageBlock = { croppedImg in
//                WmcHudManager.loading()
//                weakSelf.viewModel.uploadUserAvatar(croppedImg) { url in
//                    WmcHudManager.dismiss()
//                    weakSelf.viewModel.updateUserAvatar(imgUrl: url) {
//                        /// 刷新页面数据
//                        weakSelf.viewModel.updatedAvatar = url
//                        weakSelf.updateData()
//                        /// 头像更新成功，需要刷新
//                        WmcNotificationManager.shared.post(type: .editUserAvatarSucceed, object: ["url": url])
//                        /// 更新本地数据,因为始终拿的本地数据，除非重新登录
//                        WmcLoginManager.shared.updateLocalAvatarUrl(url: url)
//                    }
//                } failureBlock: {
//                    WmcHudManager.dismiss()
//                }
//            }
        }
    }

    private func updateAvatar(croppedImg: UIImage) {
        WmcHudManager.loading()
        self.viewModel.uploadUserAvatar(croppedImg) { [weak self] url in
            WmcHudManager.dismiss()
            guard let weakSelf = self else { return }
            weakSelf.viewModel.updateUserAvatar(imgUrl: url) {
                /// 刷新页面数据
                weakSelf.viewModel.updatedAvatar = url
                weakSelf.updateData()
                /// 头像更新成功，需要刷新
                WmcNotificationManager.shared.post(type: .editUserAvatarSucceed, object: ["url": url])
                /// 更新本地数据,因为始终拿的本地数据，除非重新登录
                WmcLoginManager.shared.updateLocalAvatarUrl(url: url)
            }
        } failureBlock: {
            WmcHudManager.dismiss()
        }
    }
}

// MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate

extension WmcCloudMineVC: UIImagePickerControllerDelegate & UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
        picker.dismiss(animated: true, completion: nil)
        let key = UIImagePickerController.InfoKey(rawValue: "UIImagePickerControllerOriginalImage")
        guard let image = info[key] as? UIImage else { return }

        let cropper = WmcCropperViewController(originalImage: image)

        cropper.delegate = self
        self.navigationController?.pushViewController(cropper, animated: true)

//        let vm = WmcImageTailorVM()
//        vm.image = WmcImage.init(uiImage: image)
//        vm.croppingImageBlock = {[weak self] croppedImg in
//            guard let weakSelf = self else { return }
//            WmcHudManager.loading()
//            weakSelf.viewModel.uploadUserAvatar(croppedImg) { url in
//                WmcHudManager.dismiss()
//                weakSelf.viewModel.updateUserAvatar(imgUrl: url) {
//                    /// 刷新页面数据
//                    weakSelf.viewModel.updatedAvatar = url
//                    weakSelf.updateData()
//                    /// 头像更新成功，需要刷新
//                    WmcNotificationManager.shared.post(type: .editUserAvatarSucceed, object: ["url": url])
//                    /// 更新本地数据,因为始终拿的本地数据，除非重新登录
//                    WmcLoginManager.shared.updateLocalAvatarUrl(url: url)
//                }
//            } failureBlock: {
//                WmcHudManager.dismiss()
//            }
//        }
//        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
//            WmcNavigatorManager.push(.imageTailor, parms: vm)
//        }
    }
}

// MARK: - UITableViewDelegate

extension WmcCloudMineVC: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let group = viewModel.dataListRelay.value.yp.object(at: indexPath.section),
           let model = group.yp.object(at: indexPath.row)
        {
            switch model.actionType {
            case .avatar:
                switch model.style {
                case .none:
                    print("")
                case .cover:
                    print("")
                case let .text(_, color: color, font: font):
                    print("")
                case .switch:
                    print("")
                case .onyAction:
                    print("")
                case let .userAvatar(_, img: img):
                    if img != "" {
                        showSheetOfChooseAavatar(showSheet: false)
                    } else {
                        showSheetOfChooseAavatar(showSheet: true)
                    }
                }
            case .editName:
                let vm = WmcEditNameVM()
                vm.updateData = { [weak self] in
                    guard let weakSelf = self else { return }
                    weakSelf.updateData()
                }
                WmcNavigatorManager.push(.editName, parms: vm)?.hidesBottomBarWhenPushed = true
            case .bindMobile:
                let vm = WmcEditPhoneVM()
                vm.updateData = { [weak self] in
                    guard let weakSelf = self else { return }
                    weakSelf.updateData()
                }
                WmcNavigatorManager.push(.editPhone, parms: vm)?.hidesBottomBarWhenPushed = true
            case .feedback:
                // 调用优化之后的h5页面
                let vm = WmcHtml5VM()
                vm.parameters = nil
                vm.questionType = .None
                vm.path = WmcHtml5VM.Html5Path.feedback
                WmcNavigatorManager.push(.html5Page, parms: vm)
            case .recommend:
                WmcNavigatorManager.push(.invitation)?.hidesBottomBarWhenPushed = true
            case .cancelAccount:
                WmcNavigatorManager.push(.cancellationAccount)?.hidesBottomBarWhenPushed = true
            case .logout:

                WmcQuitTeamAlertView.alertView(title: "确定退出当前账号？", content: "退出后，照片将停止同步到你的项目", leftBtnTitle: "取消", rightBtnTitle: "确定", confirmB: {
                    WmcLoginManager.logout()
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
                        guard let weakSelf = self else { return }
//                        weakSelf.popToSpecificVC(vcClass: WmcHomeVC.self)
                        weakSelf.navigationController?.popToRootViewController(animated: true)
                    }
                }).show()

            default: break
            }
        }
    }
}

// MARK: - UITableViewDataSource

extension WmcCloudMineVC: UITableViewDataSource {
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 0
        } else {
            return 16
        }
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView()
        headerView.backgroundColor = .wmc_grayH19_F5F5F5
        return headerView
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return .YP.Min
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.dataListRelay.value.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let group = viewModel.dataListRelay.value.yp.object(at: section) {
            return group.count
        }
        return 0
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        if let group = viewModel.dataListRelay.value.yp.object(at: indexPath.section),
//           let item = group.yp.object(at: indexPath.row)
//        {
//            return item.rowHeight
//        }
        return 57
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: WmcCloudMineCell = tableView.yp.dequeueReusableCell()
        if let group = viewModel.dataListRelay.value.yp.object(at: indexPath.section),
           let model = group.yp.object(at: indexPath.row)
        {
            cell.configModel(model)
            // 分割线
            let isNoLastSection = (indexPath.section != viewModel.dataListRelay.value.count - 1)
            let isNoLasrRow = (indexPath.row == (group.count - 1))
            cell.lineView.isHidden = isNoLastSection && isNoLasrRow
        }
        return cell
    }
}

// MARK: - WmcCropperViewControllerDelegate

extension WmcCloudMineVC: WmcCropperViewControllerDelegate {
    func cropperDidConfirm(_ cropper: WmcCropperViewController, state: WmcCropperState?) {
        if let state = state,
           let image = cropper.originalImage.cropped(withCropperState: state)
        {
            WmcHudManager.loading()
            self.viewModel.uploadUserAvatar(image) { [weak self] url in
                WmcHudManager.dismiss()
                guard let weakSelf = self else { return }
                weakSelf.viewModel.updateUserAvatar(imgUrl: url) {
                    /// 刷新页面数据
                    weakSelf.viewModel.updatedAvatar = url
                    weakSelf.updateData()
                    /// 头像更新成功，需要刷新
                    WmcNotificationManager.shared.post(type: .editUserAvatarSucceed, object: ["url": url])
                    /// 更新本地数据,因为始终拿的本地数据，除非重新登录
                    WmcLoginManager.shared.updateLocalAvatarUrl(url: url)
                }
            } failureBlock: {
                WmcHudManager.dismiss()
            }
        }
    }
}
